package com.xiaofu.datasource.aop;

import com.xiaofu.datasource.annotation.DS;
import com.xiaofu.datasource.datasource.DynamicDataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author luofuzhou
 * @date 2024/8/23
 * @dec 描述
 */
@Component
@Aspect
public class DynamicDataSourceAspect {

    @Before(value = "@annotation(com.xiaofu.datasource.annotation.DS)")
    public void switchDataSource(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        DS ds = method.getAnnotation(DS.class);
        if(ds == null){
            return;
        }
        DynamicDataSourceContextHolder.setDateSoureType(ds.value());
    }

    @After("@annotation(com.xiaofu.datasource.annotation.DS)")
    public void releaseDataSource(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        DS ds = method.getAnnotation(DS.class);
        if(ds == null){
            return;
        }
        DynamicDataSourceContextHolder.clearDateSoureType();
    }
}
